import fs from 'fs';
import path from 'path';
import os from 'os';

import Result from './result';
import logger from './logger';
import secureStore from './secureStore';

const dataDir = path.join(os.homedir(), '.my-electron-app', 'loadData');

async function baseSave(fileName, base64) {
  try {
    logger.debug(`保存文件 ${dataDir} / ${fileName}`);
    // 检查是否已经是 base64 数据 URI 格式
    let base64Data;
    if (base64.startsWith('data:image')) {
      base64Data = base64.replace(/^data:image\/\w+;base64,/, '');
    } else {
      base64Data = base64;
    }
    
    // 确保目录存在
    fs.mkdirSync(path.dirname(path.join(dataDir, fileName + '.png')), { recursive: true });
    
    let _data = secureStore.getPlain('softIcon');
    if (!_data || !Array.isArray(_data)) {
      _data = [];
    }
    
    // 检查是否已存在同名条目
    const existingIndex = _data.findIndex(p => p.name && (p.name.toLowerCase() === fileName.toLowerCase() || fileName.toLowerCase() === p.name.toLowerCase()));
    
    if (existingIndex === -1) {
      // 如果没有找到匹配项，则添加新项
      _data.push({ name: fileName, icon: 'data:image/png;base64,' + base64Data });
      logger.debug(`添加新的图标缓存: ${fileName}`);
    } else {
      // 如果找到了匹配项，则更新现有项
      _data[existingIndex] = { name: fileName, icon: 'data:image/png;base64,' + base64Data };
      logger.debug(`更新现有图标缓存: ${fileName}`);
    }
    
    secureStore.setPlain('softIcon', _data);
    
    let outputPath = path.join(dataDir, fileName + '.png');
    logger.debug(`保存文件地址: ${outputPath}`);

    // 使用 Promise 封装 writeFile - 修复Buffer弃用警告
    await new Promise((resolve, reject) => {
      // 使用 Buffer.from() 替代已弃用的 new Buffer()
      const bufferData = Buffer.from(base64Data, 'base64');
      fs.writeFile(outputPath, bufferData, (err) => {
        if (err) {
          logger.error(`保存文件失败: ${err.message}`);
          reject(Result.error(101, err.message));
        } else {
          resolve(Result.success(outputPath));
        }
      });
    });
    
    return Result.success(outputPath);
  } catch (error) {
    logger.error(`baseSave 错误: ${error.message}`);
    return Result.error(101, error.message);
  }
}

async function readBase(fileName) {
  try {
    logger.info(`开始读取文件图标: ${fileName}`);
    const filePath = path.join(dataDir, fileName + '.png');
    if (!fs.existsSync(filePath)) {
      return Result.error(102, '文件不存在');
    }
    // 同步读取文件内容 - 使用现代方法避免弃用警告
    const fileData = fs.readFileSync(filePath);
    // 转换为 Base64 字符串
    const base64String = fileData.toString('base64');
    // 返回带有 MIME 类型的 Base64 数据
    return Result.success(base64String);
  } catch (error) {
    logger.error(`readBase 错误: ${error.message}`);
    return Result.error(101, error.message);
  }
}

async function isOnBase(fileName) {
  try {
    const filePath = path.join(dataDir, fileName + '.png');
    return fs.existsSync(filePath);
  } catch (error) {
    logger.error(`isOnBase 错误: ${error.message}`);
    return false;
  }
}

export default {
  baseSave, readBase, isOnBase
}